<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-form-item label="规格名称" prop="ruleName">
          <el-input v-model="formData.ruleName" placeholder="请输入规格名称" />
        </el-form-item>
        <el-form-item label="规格属性">
          <div v-for="(spec, idx) in specList" :key="idx" style="margin-bottom: 16px;">
            <div style="display: flex; align-items: center; margin-bottom: 8px;">
              <span style="width: 60px;">{{ spec.value }}</span>
              <el-tag
                v-for="(tag, tIdx) in spec.detail"
                :key="tag + tIdx"
                closable
                @close="removeSpecValue(idx, tIdx)"
                style="margin-right: 8px;"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="spec.inputShow"
                v-model="spec.inputValue"
                size="mini"
                style="width: 100px; margin-right: 8px;"
                @keyup.enter.native="confirmSpecValue(idx)"
                @blur="confirmSpecValue(idx)"
              />
              <el-button v-else size="mini" @click="showSpecValueInput(idx)">+ 添加</el-button>
            </div>
          </div>
          <el-button type="primary" size="small" @click="showAddSpecDialog">添加新规格</el-button>
        </el-form-item>
      </el-form>
      <el-dialog title="添加规格" :visible.sync="addSpecDialogVisible" width="400px" append-to-body>
        <el-form :model="addSpecForm" label-width="70px">
          <el-form-item label="规格：">
            <el-input v-model="addSpecForm.value" placeholder="请输入规格" />
          </el-form-item>
          <el-form-item label="规格值：">
            <el-input v-model="addSpecForm.detailInput" placeholder="请输入规格值" @keyup.enter.native="addSpecDetail" />
            <div style="margin-top: 8px;">
              <el-tag
                v-for="(tag, idx) in addSpecForm.detail"
                :key="tag + idx"
                closable
                @close="removeAddSpecDetail(idx)"
                style="margin-right: 8px;"
              >
                {{ tag }}
              </el-tag>
            </div>
            <el-button size="mini" @click="addSpecDetail" style="margin-top: 8px;">添加</el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addSpecDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddSpec">确定</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确定</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as ProductRuleApi from '@/api/store/rule';
      export default {
    name: "ProductRuleForm",
    components: {
                    },
    data() {
      return {
        // 弹出层标题
        dialogTitle: "",
        // 是否显示弹出层
        dialogVisible: false,
        // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
        formLoading: false,
        // 表单参数
        formData: {
                            id: undefined,
                            ruleName: undefined,
                            ruleValue: undefined,
                            deleted: 0
        },
        // 表单校验
        formRules: {
                        ruleName: [{ required: true, message: '规格名称不能为空', trigger: 'blur' }],
        },
        specList: [],
        addSpecDialogVisible: false,
        addSpecForm: {
          value: '',
          detail: [],
          detailInput: ''
        }
      };
    },
    methods: {
      /** 打开弹窗 */
     async open(row) {
        this.dialogVisible = true;
        this.reset();
        if (row && row.id) {
          this.formData.id = row.id;
          this.formData.ruleName = row.ruleName;
          this.specList = (row.specs || []).map(item => ({
            value: item.name,
            detail: Array.isArray(item.values) ? [...item.values] : [],
            inputShow: false,
            inputValue: ''
          }));
          this.dialogTitle = "修改商品规则值(规格)";
          return;
        }
        this.dialogTitle = "新增商品规则值(规格)";
      },
      /** 提交按钮 */
      async submitForm() {
        // 校验主表
        await this.$refs["formRef"].validate();
        this.formLoading = true;
        try {
          // 组装规格数据，增加 deleted 字段
          this.formData.ruleValue = JSON.stringify(
            this.specList.map(({ value, detail }) => ({
              value,
              detail,
              deleted: 0
            }))
          );
          const data = this.formData;
          // 修改的提交
          if (data.id) {
            await ProductRuleApi.updateProductRule(data);
            this.$modal.msgSuccess("修改成功");
            this.dialogVisible = false;
            this.$emit('success');
            return;
          }
          // 添加的提交
          await ProductRuleApi.createProductRule(data);
          this.$modal.msgSuccess("新增成功");
          this.dialogVisible = false;
          this.$emit('success');
        } finally {
          this.formLoading = false;
        }
      },
                      /** 表单重置 */
      reset() {
        this.formData = {
                            id: undefined,
                            ruleName: undefined,
                            ruleValue: undefined,
                            deleted: 0
        };
        this.specList = [];
        this.addSpecDialogVisible = false;
        this.addSpecForm = { value: '', detail: [], detailInput: '' };
        this.resetForm("formRef");
      },
      showAddSpecDialog() {
        this.addSpecForm = { value: '', detail: [], detailInput: '' };
        this.addSpecDialogVisible = true;
      },
      addSpecDetail() {
        const val = this.addSpecForm.detailInput && this.addSpecForm.detailInput.trim();
        if (val && !this.addSpecForm.detail.includes(val)) {
          this.addSpecForm.detail.push(val);
        }
        this.addSpecForm.detailInput = '';
      },
      removeAddSpecDetail(idx) {
        this.addSpecForm.detail.splice(idx, 1);
      },
      confirmAddSpec() {
        if (!this.addSpecForm.value || this.addSpecForm.detail.length === 0) return;
        this.specList.push({
          value: this.addSpecForm.value,
          detail: [...this.addSpecForm.detail],
          inputShow: false,
          inputValue: ''
        });
        this.addSpecDialogVisible = false;
      },
      showSpecValueInput(idx) {
        this.$set(this.specList[idx], 'inputShow', true);
        this.$set(this.specList[idx], 'inputValue', '');
      },
      confirmSpecValue(idx) {
        const val = this.specList[idx].inputValue && this.specList[idx].inputValue.trim();
        if (val && !this.specList[idx].detail.includes(val)) {
          this.specList[idx].detail.push(val);
        }
        this.specList[idx].inputShow = false;
        this.specList[idx].inputValue = '';
      },
      removeSpecValue(specIdx, valIdx) {
        this.specList[specIdx].detail.splice(valIdx, 1);
      },
      openForm(row) {
        this.$refs["formRef"].open(row);
      }
    }
  };
</script>
